using System;
using System.Collections.Generic;
using Pathfinding;
using UnityEngine;
using Yoozoo.Managers.ResourceManagerV2.Runtime;

namespace Yoozoo.Gameplay
{
    public static class AstarPathUtils
    {
        public static ResLoader _graphLoader;
        
        public static void DeserializeGraphsAdditive(string graphPath,Action callBack = null)
        {
            if (_graphLoader == null)
            {
                _graphLoader = ResLoader.Alloc();
            }

            _graphLoader.Add2Load(graphPath, ((success, name, asset) =>
            {
                DeserializeGraphsAdditive((asset as TextAsset)?.bytes);
                callBack?.Invoke();
            }));
            
            _graphLoader.Load();
        }
        
        public static void DeserializeGraphsAdditive(object asset)
        {
            var graphs = AstarPath.active.data.graphs;

            List<NavGraph> graphList = new List<NavGraph>(4);
            for (int i = 0; i < graphs.Length; i++)
            {
                if (graphs[i]!=null)
                {
                    graphList.Add(graphs[i]);
                }
            }
            AstarPath.active.data.graphs = graphList.ToArray();
            byte[] bytes = (asset as TextAsset)?.bytes;
            AstarPath.active.data.DeserializeGraphsAdditive(bytes);
        }

        public static void ClearGraph(string graphName)
        {
            var graphs = AstarPath.active.data.graphs;
            for (int i = 0; i < graphs.Length; i++)
            {
                if (graphs[i] == null) continue;

                if (graphs[i].name == graphName)
                {
                    AstarPath.active.data.RemoveGraph(graphs[i]);
                }
            }
        }
        
        public static void ClearGraphs()
        {
            var graphs = AstarPath.active.data.graphs;
            for (int i = 0; i < graphs.Length; i++)
            {
                if (graphs[i] == null) continue;

                if (graphs[i].name == "sidewalk" ||
                    graphs[i].name == "sidewalk_road")
                {
                    AstarPath.active.data.RemoveGraph(graphs[i]);
                }
            }
        }
        public static void ClearCityGraphs()
        {
            var graphs = AstarPath.active.data.graphs;
            for (int i = 0; i < graphs.Length; i++)
            {
                if (graphs[i] == null) continue;

                if (graphs[i].name == "RandomMap")
                {
                    AstarPath.active.data.RemoveGraph(graphs[i]);
                }
            }
        }

        public static void Dispose()
        {
            ClearGraphs();
            if (_graphLoader != null)
            {
                _graphLoader.Recycle2Cache();
                _graphLoader = null;
            }
        }
        
    }
}
